<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1>관리자 페이지 로그인</h1>
        <p>관리자 또는 파트너 계정으로 로그인하세요</p>
      </div>

      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="identifier">로그인 ID 또는 이메일</label>
          <input
            id="identifier"
            v-model="loginForm.identifier"
            type="text"
            required
            placeholder="로그인 ID 또는 이메일을 입력하세요"
            :disabled="loading"
          />
        </div>

        <div class="form-group">
          <label for="password">비밀번호</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            required
            placeholder="비밀번호를 입력하세요"
            :disabled="loading"
          />
        </div>

        <div class="form-group">
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="loginForm.rememberMe"
              :disabled="loading"
            />
            로그인 상태 유지 (30일)
          </label>
        </div>

        <div class="form-group">
          <button
            type="submit"
            class="login-btn"
            :disabled="loading || !canSubmit"
          >
            {{ loading ? '로그인 중...' : '로그인' }}
          </button>
        </div>

        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const errorMessage = ref('')

const loginForm = ref({
  identifier: '',
  password: '',
  rememberMe: false,
})

const canSubmit = computed(() => {
  return loginForm.value.identifier.trim() && loginForm.value.password.trim()
})

async function handleLogin() {
  if (!canSubmit.value) return

  loading.value = true
  errorMessage.value = ''

  try {
    const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

    const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        identifier: loginForm.value.identifier.trim(),
        password: loginForm.value.password,
        rememberMe: loginForm.value.rememberMe,
      }),
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.error || '로그인 실패')
    }

    const userData = await response.json()

    // 获取用户详细信息以确定角色
    const meResponse = await fetch(`${API_BASE_URL}/api/auth/me`, {
      credentials: 'include',
    })

    if (!meResponse.ok) {
      throw new Error('사용자 정보 가져오기 실패')
    }

    const userInfo = await meResponse.json()

    // 检查用户角色权限
    if (userInfo.role !== 'admin' && userInfo.role !== 'partner') {
      throw new Error('관리자 페이지 접근 권한이 없습니다')
    }

    // 保存用户信息到store
    authStore.setToken('logged-in') // 简单标记已登录
    authStore.user = {
      id: userInfo.id,
      name: userInfo.name || userInfo.nickname || userInfo.loginId,
      role: userInfo.role,
      loginId: userInfo.loginId,
      email: userInfo.email,
    }

    // 跳转到仪表盘
    router.push('/dashboard')
  } catch (error: any) {
    console.error('로그인 실패:', error)
    errorMessage.value = error.message || '로그인 실패, 다시 시도하세요'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-header h1 {
  color: #333;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-group input[type="text"],
.form-group input[type="password"] {
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-group input[type="text"]:focus,
.form-group input[type="password"]:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.checkbox-label {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  cursor: pointer;
}

.checkbox-label input[type="checkbox"] {
  margin: 0;
}

.login-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 14px 20px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.login-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 12px 16px;
  border-radius: 8px;
  border: 1px solid #fcc;
  font-size: 14px;
  text-align: center;
}

@media (max-width: 480px) {
  .login-card {
    padding: 24px;
  }

  .login-header h1 {
    font-size: 20px;
  }
}
</style>
